var path=require('path');
var express=require('express');
var session=require('express-session');
var MongoStore=require('connect-mongo')(session);
var flash=require('connect-flash');
var config=require('./config/deafult.js');
var routes=require('./routes');
var pkg=require('./package.json');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    name:config.session.key,//设置 cookie 中保存 session id 的字段名称
    secret:config.session.secret,//加密cookie的盐
    resave:true,//强制刷新session
    saveUninitialized:false,//强制创建一个Session，即使用户未登录
    cookie:{
        maxAge:config.session.maxAge//过期时间，过期后cookie中的session id自动删除
    },
    store:new MongoStore({//将session存储到mongodb
        url:config.mongodb
    })
}));
app.use(flash());
app.use(require('express-formidable')({
    uploadDir:path.join(__dirname,'public/uploads'),
    keepExtensions:true//保留后缀
}));

//全局常量
app.locals.blog={
    title:pkg.name,
    description:pkg.description
};

//会话变量
app.use((req,res,next)=>{
    res.locals.user=req.session.user;
    res.locals.success=req.flash('success').toString();
    res.locals.error=req.flash('error').toString();
    next();
});

routes(app);

if(module.parent){
    module.exports=app;
}else{
    app.listen(config.port,()=>{
        console.info(`============== ${pkg.name} port:${config.port} ==== ${new Date().toLocaleString()} ==============`);
    });
}
